<template>
  <div class="page-system-settings-user">
    <TableLayout>
      <template v-slot:search>
        <div class="search-item">
          <el-input v-model="searchForm.deptName" placeholder="请输入科室名称" prefix-icon="el-icon-search" />
        </div>
        <div class="search-item">
          <el-input v-model="searchForm.userName" placeholder="请输入用户名称" />
        </div>
        <div class="search-item">
          <el-input v-model="searchForm.phonenumber" placeholder="请输入手机号码" />
        </div>
        <div class="search-item">
          <el-select v-model="searchForm.status" placeholder="用户状态">
            <el-option disabled label="请选择" value="" />
            <el-option label="正常" value="0" />
            <el-option label="停用" value="1" />
          </el-select>
        </div>
        <div class="search-item">
          <el-date-picker
            v-model="searchForm.date"
            type="daterange"
            start-placeholder="创建时间"
            end-placeholder="创建时间"
            range-separator="-"
            value-format="timestamp"
          />
        </div>
        <div class="search-item">
          <pure-button type="minor" label="查询" icon="search" @click="onSearch" />
          <pure-button type="patch" label="重置" icon="reset" @click="onReset" />
        </div>
      </template>
      <template v-slot:operate>
        <pure-button type="special" label="新增" icon="download" @click="onAdd" />
        <pure-button type="major" label="导入" icon="upload" />
      </template>
      <div class="content-box">
        <el-tree class="tree" :data="departmentData" />
        <div class="main-content">
          <div class="table-box">
            <el-table ref="tableRef" :data="tableData" height="100%" @selection-change="onSelectionChange">
              <el-table-column type="selection" width="55" />
              <el-table-column type="index" label="序号" width="60" />
              <el-table-column label="用户名称" prop="userName" />
              <el-table-column label="用户昵称" prop="nickName" />
              <el-table-column label="科室" prop="dept" :formatter="formatDept" />
              <el-table-column label="电话号码" prop="phonenumber" />
              <el-table-column label="状态">
                <template slot-scope="{ row }">
                  <el-switch :value="row.status" active-value="0" inactive-value="1" @change="onChangeStatus(row)" />
                </template>
              </el-table-column>
              <el-table-column label="创建时间" prop="createTime" />
              <el-table-column label="操作">
                <template slot-scope="{ row }">
                  <span class="operate-btn" @click="onEdit(row)">修改</span>
                  <span class="operate-btn delete" @click="onDel(row.userId)">删除</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="table-footer">
            <div class="operate-box">
              <div class="operate-item">
                <el-checkbox v-model="allChecked" label="全选" :indeterminate="allCheckedIndeterminate" @change="onToggelAllCheck" />
              </div>
              <div class="operate-item" @click="onBatchDel">
                <i class="el-icon-delete" />
                <span>批量删除</span>
              </div>
              <span class="checked-num">已选：{{ checkedNum }}条</span>
            </div>
            <el-pagination
              :page-sizes="[20, 50, 100, 200]"
              layout="total, sizes, prev, pager, next, jumper"
              background
              :current-page="currentPage"
              :page-size="pageSize"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
    </TableLayout>
    <custom-drawer
      :wrapper-closable="false"
      :title="dialogTitle"
      :visible.sync="showAddEditDialog"
      @closed="onDialogClosed"
    >
      <CompFormBox title="基础信息">
        <CompAddEdit ref="compAddEditRef" :department-tree-data="departmentData" :current-data="currentData" :operate-type="operateType" />
      </CompFormBox>
      <template v-slot:footer>
        <div>
          <pure-button label="保存" @click="onSave" />
          <pure-button v-if="operateType === 'add'" label="保存并继续新增" type="major" @click="onSaveThenAdd" />
          <pure-button label="取消" type="patch" @click="onCancel" />
        </div>
      </template>
    </custom-drawer>
  </div>
</template>

<script>
import pageMixin from '@/mixins/page';
import CompFormBox from '@/common/components/formBox/index.vue';
import CompAddEdit from './components/add-edit.vue';
import { getList, changeStatus, add as addUser, edit as editUser, del as delUser, } from './api';

export default {
  components: {
    CompFormBox,
    CompAddEdit,
  },
  mixins: [
    pageMixin,
  ],
  data() {
    return {
      departmentData: [
        {
          label: '华西院区',
          id: 1,
          children: [
            {
              label: '骨科',
              id: 2,
            },
            {
              label: '外科',
              id: 3,
            },
          ],
        },
        {
          label: '锦江院区',
          id: 4,
          children: [
            {
              label: '产科',
              id: 5,
            },
            {
              label: '外科',
              id: 6,
            },
          ],
        },
      ],
      searchForm: {},
      tableColumns: [
        {
          label: '用户名称',
          prop: 'name',
        },
        {
          label: '用户昵称',
          prop: 'name',
        },
        {
          label: '科室',
          prop: 'name',
        },
        {
          label: '电话号码',
          prop: 'name',
        },
        {
          label: '状态',
          prop: 'name',
        },
        {
          label: '创建时间',
          prop: 'name',
        },
      ],
      tableData: [],
      checkedNum: 0,
      allChecked: false,
      allCheckedIndeterminate: false,
      operateType: 'add',
      showAddEditDialog: false,
      currentData: {},
      loading: false,
    };
  },
  computed: {
    dialogTitle() {
      const titles = {
        add: '新增用户',
        edit: '编辑用户',
      };
      return titles[this.operateType];
    },
  },
  created() {
    this.getListData();
  },
  methods: {
    formatDept(row) {
      return row?.dept?.deptName ?? '-';
    },
    getListData() {
      const loading = this.showLoading();
      const { date, ...rest } = this.searchForm;
      const params = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        ...rest,
      };
      if (date) {
        const [
          startTime,
          endTime,
        ] = date;
        params.startTime = startTime;
        params.endTime = endTime;
      }
      getList(params).then((data) => {
        const { rows, total, } = data.data;
        this.total = total;
        this.tableData = rows;
      }).finally(() => {
        loading.close();
      });
    },
    onReset() {
      this.searchForm = {};
      this.onSearch();
    },
    onAdd() {
      this.operateType = 'add';
      this.currentData = {
        status: '0',
      };
      this.showAddEditDialog = true;
    },
    onEdit(data) {
      this.operateType = 'edit';
      const {
        userId,
        nickName,
        dept,
        phonenumber,
        userName,
        password,
        status,
      } = data;
      this.currentData = {
        userId,
        nickName,
        dept,
        phonenumber,
        userName,
        password,
        status,
      };
      this.showAddEditDialog = true;
    },
    onCancel() {
      this.showAddEditDialog = false;
    },
    onDialogClosed() {
      this.$refs.compAddEditRef.reset();
    },
    onSelectionChange(selection) {
      this.checkedNum = selection.length;
      if (selection.length === 0) {
        this.allChecked = false;
        this.allCheckedIndeterminate = false;
      } else if (selection.length < this.tableData.length) {
        this.allChecked = false;
        this.allCheckedIndeterminate = true;
      } else {
        this.allChecked = true;
        this.allCheckedIndeterminate = false;
      }
    },
    onToggelAllCheck(checked) {
      this.$refs.tableRef.toggleAllSelection();
    },
    onChangeStatus(data) {
      const { userId, status, } = data;
      const newStatus = status === '1' ? '0' : '1';
      const params = {
        userId,
        status: newStatus,
      };
      changeStatus(params).then(() => {
        this.$message.success('操作成功');
        this.getListData();
      });
    },
    submitData() {
      this.loading = true;
      const { valid, data, } = this.$refs.compAddEditRef.validate();
      if (valid) {
        const request = this.operateType === 'edit' ? editUser : addUser;
        request(data)
          .then(() => {
            this.$message.success('操作成功');
            this.getListData();
            if (this.continueAdd) {
              this.$refs.compAddEditRef.reset();
            } else {
              this.showAddEditDialog = false;
            }
          })
          .finally(() => {
            this.loading = false;
          });
      } else {
        this.loading = false;
        this.$message.error('请正确填写');
      }
    },
    onSave() {
      this.continueAdd = false;
      this.submitData();
    },
    onSaveThenAdd() {
      this.continueAdd = true;
      this.submitData();
    },
    sumbitDelete(ids) {
      const loading = this.showLoading({ text: '操作中...', });
      delUser(ids.join())
        .then(() => {
          // 处理最后一页最后一条数据删除分页显示问题
          this.calcLastPage(ids.length);
          this.getListData();
          this.$message({
            type: 'success',
            message: '删除用户成功',
          });
        })
        .finally(() => {
          loading.close();
        });
    },
    onDel(id) {
      this.$confirm('此操作将删除选中用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.sumbitDelete([
            id,
          ]);
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消',
          });
        });
    },
    onBatchDel() {
      const tableRef = this.$refs.tableRef;
      const selected = tableRef.selection;
      if (!selected.length) {
        this.$message.error('请至少选中一个用户');
        return false;
      }
      const userIds = selected.map(item => item.userId);
      this.$confirm('此操作将删除选中用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.sumbitDelete(userIds);
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消',
          });
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.page-system-settings-user {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.content-box {
  height: 100%;
  flex: auto;
  display: flex;
  padding: 10px;
  background: #fff;
  .tree {
    flex: 0 0 260px;
    border-right: 1px solid #dde9e8;
  }
  .main-content {
    flex: auto;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    .table-box {
      flex: auto;
      overflow: hidden;
      min-height: 100px;
      .operate-btn {
        margin-right: 16px;
        font-size: 14px;
        color: #006666;
        cursor: pointer;
        &.delete {
          color: #ff836b;
        }
      }
    }
  }
}
</style>
